<template>
	<view class="xs-storelist">
		<view class="store" v-if="storeInfo.item.name != ''">
			<image src="http://pets.wx.bwicc.com/assets/address.png" mode="widthFix"></image>
			<text>{{ storeInfo.item.name }}</text>
			-
			<text>{{ storeInfo.shop.name }}</text>
			<text class="check-store" @click="checkStore">切换门店</text>
		</view>
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
			<view class="store-list">
				<view class="store-item-close" @click="closePopup">
					<image src="../../static/images/close.png" mode="widthFix"></image>
				</view>
				<view class="store-item" v-for="item in storeList" :key="item.id">
					<view class="store-item-name">
						{{ item.name }}
					</view>
					<view class="store-shops">
						<view class="store-shop-item" v-for="shop in item.store" :key="shop.id">
							<view class="store-shop-item-name">
								<view>
									{{ shop.name }}
									<text style="color: #9e9e9e; font-size: 13px; margin-left: 10px">{{
                    getDistance(shop)
                  }}</text>
								</view>
								<button type="primary" size="mini" :disabled="shop.id == storeInfo.shop.id" @click="toRent(item, shop)">
									去租赁
								</button>
							</view>
							<view class="store-shop-item-address">
								<image src="http://pets.wx.bwicc.com/assets/address.png" mode="widthFix"></image>
								{{ shop.address }}
							</view>
							<view class="store-shop-item-time">
								<image src="http://pets.wx.bwicc.com/assets/time.png" mode="widthFix"></image>
								营业时间：{{ shop.businesshours }}
							</view>
							<view class="store-shop-item-phone">
								<image src="http://pets.wx.bwicc.com/assets/tel.png" mode="widthFix"></image>
								店铺电话：{{ shop.phone }}
							</view>
							<view class="store-shop-item-phone">
								<image src="http://pets.wx.bwicc.com/assets/cout.png" mode="widthFix"></image>
								可租赁数量：{{ shop.stock == null ? 0 : shop.stock }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	export default {
		name: "xsStorelist",
		props: {
			load: {
				type: Function,
				default: () => {},
			},
		},
		data() {
			return {
				css: this.$xyfun.css(), // 公共样式
				location: "", // 当前定位信息
				storeList: [], // 门店列表
				storeInfo: {
					item: {
						name: "",
					},
					shop: {},
				}, // 当前选中的门店信息
				store: {
					address: "",
					distance: "",
					id: "",
					lat: "",
					lng: "",
					name: "",
					stores: [],
				}, // 预留字段，暂未使用
			};
		},
		// 下拉刷新时重新获取定位和门店列表
		onPullDownRefresh() {
			this.getLocation();
		},
		// 组件挂载时获取定位和门店列表
		mounted() {
			this.getLocation();
		},
		onShow() {
			this.getLocation();
		},
		methods: {
			/**
			 * 获取距离并格式化为字符串
			 * @param {Object} item 门店对象，需包含distance字段
			 * @returns {String} 距离字符串，单位km
			 */
			getDistance(item) {
				let distance = item.distance;
				return Number(distance).toFixed(2) + "km";
			},
			/**
			 * 获取当前定位信息
			 * 成功后调用getStoreList获取门店列表
			 */
			getLocation() {
				let that = this;
				uni.getLocation({
					type: "wgs84",
					success: function(res) {
						that.location = res;
						that.getStoreList();
					},
					fail: function(err) {
						console.log(err);
						that.location = "获取位置失败";
					},
				});
			},
			/**
			 * 获取门店列表
			 * 根据当前定位信息请求后端接口
			 * 成功后调用getStoreInfo获取当前选中的门店
			 */
			getStoreList() {
				let that = this;
				this.$api.get({
					url: "/store/store/store_list",
					loadingTip: "加载中...",
					data: {
						lat: that.location.latitude,
						lng: that.location.longitude,
					},
					success: (res) => {
						that.storeList = res;
						that.getStoreInfo();
					},
				});
			},
			/**
			 * 打开门店选择弹窗
			 */
			checkStore() {
				this.$refs.popup.open();
				// uni.navigateTo({
				//   url: "/pages/realname/index",
				// });
			},
			/**
			 * 获取本地缓存的门店信息
			 * 如果有则赋值并触发load事件
			 * 如果没有则弹出门店选择弹窗
			 */
			getStoreInfo() {
				let storeInfo = uni.getStorageSync("storeInfo");
				if (storeInfo) {
					this.storeInfo = storeInfo;
					this.$emit("load");
				} else {
					// console.log(this.storeList)
					// let merged = this.storeList.flatMap(item => item.store)
					// const minObj = merged.reduce((min, cur) =>
					// 	cur.distance < min.distance ? cur : min
					// )
					let result = this.storeList.reduce((min, item) => {
						item.store.forEach(sub => {
							if (!min || sub.distance < min.shop.distance) {
								min = {
									item: item,
									shop: sub
								};
							}
						});
						return min;
					}, null);

					uni.setStorageSync("store_id", result.shop.id);
					uni.setStorageSync("storeInfo", result);
					this.storeInfo = result
					this.$emit("load");
				}
			},
			/**
			 * 切换门店
			 * @param {Object} item 门店对象
			 * @param {Object} shop 门店下的具体门店（分店）对象
			 * 设置store_id和storeInfo到本地缓存，关闭弹窗并触发load事件
			 */
			toRent(item, shop) {
				let store_id = shop.id;
				this.storeInfo = {
					item,
					shop,
				};
				console.log(this.storeInfo);
				uni.setStorageSync("store_id", store_id);
				uni.setStorageSync("storeInfo", this.storeInfo);
				this.$refs.popup.close();
				this.$emit("load");
			},
			closePopup() {
				this.$refs.popup.close();
			},
		},
	};
</script>
<style lang="scss">
	.xs-storelist {
		border-radius: 10px;
		margin: 0 15px;
		margin-bottom: 0;
		margin-top: 30rpx;
	}

	.store {
		display: flex;
		align-items: center;
		justify-content: flex-start;

		text.check-store {
			margin-left: 20rpx;
			color: #007aff;
		}

		image {
			width: 36rpx;
			height: 36rpx;
		}
	}

	.store-list {
		height: calc(100vh - 100rpx);
		overflow-y: auto;
		border-radius: 20rpx 20rpx 0 0;
		background: #fafafb;
		padding: 20rpx;

		.store-item-close {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100rpx;

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.store-item {
			background: #fff;
			padding: 20rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;

			.store-item-name {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.store-shops {
				.store-shop-item {
					border-radius: 10rpx;
					margin-top: 20rpx;
					padding: 20rpx;
					box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);

					view {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						line-height: 60rpx;
					}

					image {
						width: 36rpx;
						height: 36rpx;
						margin-right: 10rpx;
					}

					.store-shop-item-name {
						margin-bottom: 10rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
				}
			}
		}
	}
</style>